<template>
  <ele-page>
    <!-- 搜索表单 -->
    <search @search="reload" :action="props.action" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        border
        stripe
        :where="defaultWhere"
      >
        <template #toolbar v-if="props.action == 'list'">
          <el-button
            type="success"
            class="ele-btn-icon"
            :icon="Plus"
            @click="openEdit()"
          >
            添加车辆
          </el-button>
          <file
            style="margin: 0px 8px"
            botton-text="批量导入"
            @done="onUpladDone"
          />
          <el-button
            type="warning"
            class="ele-btn-icon"
            :icon="DocumentCopy"
            @click="exportExcel()"
          >
            导出表格
          </el-button>
        </template>
        <template #status="{ row }">
          <el-tag :type="row.statusType">{{ row.status }}</el-tag>
        </template>
        <template #plate_number="{ row }">
          <span class="blue pointer" @click="openDetail(row)">{{
            row.plate_number
          }}</span>
        </template>
        <template #profit="{ row }">
          <span class="blue pointer" @click="openMoneyDetail(row)">{{
            row.profit
          }}</span>
        </template>
        <template #insurance_date_c="{ row }">
          <span
            :class="deadlinClass(row.insurance_date_c_out)"
            @click="openInsurance(row, '全部')"
            >{{ row.insurance_date_c }}</span
          >
        </template>
        <template #insurance_date_b="{ row }">
          <span
            :class="deadlinClass(row.insurance_date_b_out)"
            @click="openInsurance(row, '全部')"
            >{{ row.insurance_date_b }}</span
          >
        </template>
        <template #actionChoose="{ row }">
          <el-button type="success" size="small" @click="choose(row)">
            选择
          </el-button>
        </template>
        <template #action="{ row }">
          <!-- <span v-if="row.status === 9999">/</span>
          <el-button-group v-else>
            <el-button type="success" size="small" @click="openOffer(row)">
              报价申请
            </el-button>
            <el-button type="warning" size="small" @click="openEdit(row)"
              >编辑</el-button
            >

            <el-button type="danger" size="small" @click="del(row)"
              >删除</el-button
            >
          </el-button-group> -->

          <el-dropdown
            @command="handleCommand"
            :show-timeout="0"
            v-if="row.status != '转出'"
          >
            <el-button type="primary" size="small">
              操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="beforeHandleCommand(row, '买保险')"
                  >买保险</el-dropdown-item
                >
                <el-dropdown-item :command="beforeHandleCommand(row, '报价')"
                  >报价</el-dropdown-item
                >

                <el-dropdown-item
                  :command="beforeHandleCommand(row, '添加收支')"
                  divided
                  >添加收支</el-dropdown-item
                >
                <el-dropdown-item :command="beforeHandleCommand(row, '出单')"
                  >出单</el-dropdown-item
                >
                <!-- <el-dropdown-item :command="beforeHandleCommand(row, '退保')"
                  >退保</el-dropdown-item
                > -->
                <el-dropdown-item
                  :command="beforeHandleCommand(row, '报价申请')"
                  >报价申请</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  :command="beforeHandleCommand(row, '编辑')"
                  >编辑基本资料</el-dropdown-item
                >
                <el-dropdown-item
                  :command="beforeHandleCommand(row, '证件图片')"
                  >证件图片</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  :command="beforeHandleCommand(row, '转出')"
                  >转出</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  :command="beforeHandleCommand(row, '删除')"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <edit v-model="showEdit" :data="current" @done="reload" />
    <!-- 处理结果提示页面 -->
    <ele-modal :width="700" title="处理结果" v-model="showImportRes">
      <div style="line-height: 25px" v-for="item in warningText" :key="item">{{
        item
      }}</div>
    </ele-modal>
    <!-- 处理结果提示页面 -->

    <!-- 出单申请 -->
    <create-trade v-model="showCreateTrade" :data="current" @done="reload" />
    <!-- 图片资料 -->
    <images v-model="showImages" :data="current" @done="reload" />
    <!-- 车辆转出 -->
    <out v-model="showOut" :data="null" :vehicle-id="outVehicleId" />
    <!-- 车辆详情 -->
    <detail v-model="showDetail" :data="current" :vehicle-id="currentId" />
    <!-- 车辆保险信息 -->
    <insurance v-model="showInsurance" :data="current" :cate="currentCate" />
    <!-- 报价申请 -->
    <insurancePlan v-model="showInsurancePlan" :data="current" />
    <!-- 添加收支 -->
    <CreateIncomeExpense v-model="showVehicleIncomeExpense" :vehicle="current" />
    <!-- 开支列表 -->
    <IncomeExpenseList
      v-model="showMoneyDetail"
      :vehicle-id="currentVehicleId"
      :plate-number="currentPlateNumber"
    />
    <!-- 买保险 -->
    <update-insurance
      v-model="showUpdateInsurance"
      :data="current"
      @done="reload"
    />
    <!-- 报价 -->
    <CreateOffer
      v-model="showOffer"
      :vehicle-id="vehicleId"
      :plate-number="plateNumber"
      @done="reload"
    />
  </ele-page>
</template>

<script setup>
  import { ref } from 'vue';
  import Search from './components/search.vue';
  import { Plus, ArrowDown, DocumentCopy } from '@element-plus/icons-vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { ElMessageBox } from 'element-plus/es';
  import {
    pageVehicleList,
    importVehicleFromExcel,
    exportVehicleList,
    delVehicle
  } from '@/api/company';
  import CreateOffer from '@/views/insurance/components/create.vue';
  import IncomeExpenseList from '@/views/vehicle/components/cost.vue';
  import CreateIncomeExpense from '@/views/vehicle/cost/components/cost.vue';
  import Edit from './components/edit.vue';
  import Detail from './components/detail.vue';
  import Images from './components/images.vue';
  import Insurance from './components/insurance.vue';
  import Out from './components/out.vue';
  import UpdateInsurance from './components/update-insurance.vue';

  import file from '@/components/FileUpload/file.vue';

  import CreateTrade from '@/views/trade/components/create.vue';
  import insurancePlan from '@/views/insurance/components/create-plan.vue';

  const props = defineProps({
    /** 修改回显的数据 */
    action: {
      type: String,
      default: 'list'
    }
  });
  /** 表格实例 */
  const tableRef = ref(null);

  /** 选择车辆用表格列配置 */
  const columnsChoose = ref([
    {
      prop: 'id',
      label: 'ID',
      width: 85,
      align: 'center'
    },
    {
      columnKey: 'actionChoose',
      label: '操作',
      slot: 'actionChoose',
      width: 75,
      align: 'center'
    },
    {
      width: 120,
      slot: 'plate_number',
      label: '车牌号码'
    },
    {
      width: 70,
      align: 'center',
      prop: 'area',
      label: '区域'
    },
    {
      prop: 'company',
      label: '车队'
    }
  ]);
  /** 列表的列 */
  const columnsList = ref([
    {
      prop: 'id',
      label: 'ID',
      width: 85,
      align: 'center'
    },
    {
      width: 70,
      align: 'center',
      prop: 'area',
      label: '区域'
    },
    {
      width: 80,
      align: 'center',
      slot: 'status',
      label: '状态'
    },
    {
      width: 120,
      slot: 'plate_number',
      label: '车牌号码'
    },
    {
      prop: 'company',
      label: '车队'
    },
    {
      width: 100,
      prop: 'realname',
      label: '车主'
    },
    {
      width: 120,
      prop: 'tel',
      label: '联系电话'
    },
    {
      width: 120,
      prop: 'reg_date',
      label: '登记日期'
    },
    {
      width: 120,
      slot: 'insurance_date_c',
      label: '交强险到期'
    },
    {
      width: 120,
      slot: 'insurance_date_b',
      label: '商业险到期'
    },
    {
      width: 120,
      prop: 'business_date',
      label: '营运有效期'
    },
    {
      width: 120,
      slot: 'profit',
      label: '车辆利润'
    },

    {
      columnKey: 'action',
      label: '操作',
      slot: 'action',
      width: 100,
      align: 'center',
      fixed: 'right'
    }
  ]);

  const columns =
    props.action == 'list' ? columnsList.value : columnsChoose.value;

  /** 表格选中数据 */
  const selections = ref([]);

  /** 当前编辑数据 */
  const current = ref(null);

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  const defaultWhere = ref({
    status: '正常'
  });

  /** 表格数据源 */
  const datasource = ({ page, limit, where, orders }) => {
    return pageVehicleList({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  /** 过期的显示红色 */
  const deadlinClass = (value) => {
    const ut = {
      0: 'pointer blue',
      1: 'pointer red'
    };
    return ut[value];
  };

  /** 报价 */
  const showOffer = ref(false);
  const vehicleId = ref(0);
  const plateNumber = ref('');

  const openOffer = (row) => {
    vehicleId.value = row.id;
    plateNumber.value = row.plate_number;
    showOffer.value = true;
  };

  /** 操作 */
  const beforeHandleCommand = (row, command) => {
    return {
      row,
      command
    };
  };
  const handleCommand = (param) => {
    let action = param.command;
    let row = param.row;
    switch (action) {
      case '买保险':
        openUpdateInsurance(row);
        break;
      case '报价申请':
        openInsurancApply(row);
        break;
      case '添加收支':
        openCreateIncomeExpense(row);
        break;
      case '出单':
        openCreateTrade(row);
        break;
      case '编辑':
        openEdit(row);
        break;
      case '证件图片':
        openImages(row);
        break;
      case '删除':
        del(row);
        break;
      case '转出':
        openOut(row);
        break;
      case '报价':
        openOffer(row);
        break;

      default:
        break;
    }
  };

  /** 搜索 */
  const reload = (where) => {
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 打开编辑弹窗 */
  const openEdit = (row) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /** 车辆详情 */
  const currentId = ref(0);
  const showDetail = ref(false);
  const openDetail = (row) => {
    currentId.value = row.id;
    current.value = row ?? null;
    showDetail.value = true;
  };

  /** 出单 */
  const showCreateTrade = ref(false);
  const openCreateTrade = (row) => {
    current.value = row ?? null;
    showCreateTrade.value = true;
  };

  /** 买保险 */
  const showUpdateInsurance = ref(false);
  const openUpdateInsurance = (row) => {
    current.value = row ?? null;
    showUpdateInsurance.value = true;
  };

  /** 保险信息 */
  const showInsurance = ref(false);
  const currentCate = ref('全部');
  const openInsurance = (row, cate) => {
    current.value = row ?? null;
    currentCate.value = cate;
    showInsurance.value = true;
  };

  /** 报价申请 */
  const showInsurancePlan = ref(false);
  const openInsurancApply = (row) => {
    current.value = row ?? null;
    showInsurancePlan.value = true;
  };

  /** 添加收支 */
  const showVehicleIncomeExpense = ref(false);
  const openCreateIncomeExpense = (row) => {
    current.value = row ?? null;
    showVehicleIncomeExpense.value = true;
  };

  /** 车辆开支详情 */
  const currentPlateNumber = ref('');
  const currentVehicleId = ref(0);
  const showMoneyDetail = ref(false);
  const openMoneyDetail = (row) => {
    currentPlateNumber.value = row.plate_number;
    currentVehicleId.value = row.id;
    showMoneyDetail.value = true;
  };

  /** 证件图片 */
  const showImages = ref(false);
  const openImages = (row) => {
    showImages.value = true;
    current.value = row ?? null;
  };

  /** 证件图片 */
  const outVehicleId = ref(0);
  const showOut = ref(false);
  const openOut = (row) => {
    showOut.value = true;
    current.value = row;
    outVehicleId.value = row.id;
  };

  /** 批量发工资文件上传完成 */
  const showImportRes = ref(false);
  const warningText = ref([]);
  const onUpladDone = (e) => {
    console.log(e, '上传完成');
    const requestData = {
      url: e
    };
    importVehicleFromExcel(requestData)
      .then((res) => {
        warningText.value = res;
        showImportRes.value = true;
        reload();
      })
      .catch(() => {});
  };

  /** 选择 */
  const emit = defineEmits(['done']);
  const choose = (row) => {
    emit('done', row);
  };

  /** 导出表格 */
  const exportExcel = () => {
    const loading = EleMessage.loading('请求中..');
    tableRef.value?.fetch(({ where }) => {
      // 方法的参数与数据源的完全一致
      // 请求查询全部接口
      console.log(where);
      var requestData = where;
      requestData.limit = 99999999;
      requestData.page = 1;

      exportVehicleList(requestData)
        .then((res) => {
          loading.close();
          window.open(res);
        })
        .catch(() => {
          loading.close();
        });
    });
  };

  // 删除
  const del = (row) => {
    ElMessageBox.confirm('确定要删除' + row.plate_number + '吗？', '系统提示', {
      type: 'warning',
      draggable: true
    })
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        delVehicle({ id: row.id })
          .then(() => {
            loading.close();
            EleMessage.success('操作成功');
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };
</script>
